$(function () {

    // 在全局作用域内创建roleIdArray
    window.messageIdArray = new Array();

    showpage()

});
function showpage() {
    $.ajax({
        url: "/message/query/to/all",
        type: "post",
        dataType: "JSON",
        success: function (result) {
            if (result.result == "SUCCESS") {
                //解析数据
                $("#messageTableBody").empty()
                //获取集合数据
                var list = result.data
                //判断list有效
                if (list.length == 0) {
                    $("#messageTableBody")
                        .append("<tr><td colspan='4' style='text-align:center;'>没有查询到数据！</td></tr>");
                    return;
                } else {
                    for (var i = 0; i < list.length; i++) {
                        var message = list[i];
                        //数据
                        var numberTd = "<td>" + (i + 1) + "</td>";
                        var messageNameTd = "<td>" + message.content + "</td>";

                        //按钮
                        var pencilBtn = "<button messageId='"+list[i].id+"' type='button' class='btn btn-primary btn-xs editBtn'><i class=' glyphicon glyphicon-pencil'></i></button>";
                        var btnTd = "<td>"+
                             pencilBtn +  "</td>";

                        var tr = "<tr>" + numberTd  + messageNameTd + btnTd + "</tr>";

                        // 将前面拼好的HTML代码追加到#roleTableBody中
                        $("#messageTableBody").append(tr);
                    }


                }

            } else {
                layer.msg(result.message);

            }

        }
    });
}
//修改
$("#messageTableBody").on("click",".editBtn",function () {
    // 1.获取当前按钮的roleId
    window.messageIdArray = $(this).attr("messageId");
    var messageName=$(this).parents("tr").children("td:eq(2)").text();
    $("#messageNameInputEdit").val(messageName);
    $("#messageeditModal").modal("show");

})
//确认修改
$("#editModalBtn").click(function () {
    // 1.获取文本框值
    var messageName = $.trim($("#messageNameInputEdit").val());

    if(messageName.length==0) {
        layer.msg("请输入有效角色名称！");

        return ;
    }
    $.ajax({
        url:"/message/update",
        type:"post",
        data:{
            "id":window.messageIdArray,
            "name":messageName
        },
        dataType:"json",
        success:function (response) {
            var result = response.result;
            if(result == "SUCCESS") {
                layer.msg("操作成功！");
                // 3.操作成功重新分页
                showpage();
            }
            if(result == "FAILED") {
                layer.msg(response.message);
            }

            // 4.不管成功还是失败，关闭模态框
            $("#messageeditModal").modal("hide");
        }
    });
});